package com.zhou.org.config;

import com.zhou.framework.constant.CacheKeyEnum;
import com.zhou.framework.redis.util.RedisUtil;
import com.zhou.org.dao.Right;
import com.zhou.org.service.RightService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author lang.zhou
 * @date 2022/5/6 16:55
 */
@Configuration
@Slf4j
public class RightConfig {
    private RedisUtil redisUtil ;
    private static RightService rightService ;

    public RightConfig(RedisUtil redisUtil, RightService service) {
        this.redisUtil = redisUtil;
        rightService = service;
    }

    private String getKey(String rightKey, String rightType, int orgId){
        return rightKey+"||||"+rightType+"||||"+orgId;
    }
    public Map<String, Right> getRightMap(String rightKey, String rightType, int orgId){
        String key = getKey(rightKey, rightType, orgId);
        Map<String,Right> rights = redisUtil.getHash(CacheKeyEnum.AUTH, key);
        if(rights == null){
            rights = rightService.getRightMapBy(rightKey,rightType,orgId);
            redisUtil.setHash(CacheKeyEnum.AUTH,key,rights);
        }
        return rights;
    }
    public List<Right> getRight(String rightKey,String rightType,int orgId){
        List<Right> rights = null;
        Map<String,Right> map = getRightMap(rightKey, rightType, orgId);
        if(map != null){
            rights = new ArrayList<>(map.size());
            rights.addAll(map.values());
        }
        return rights;
    }
    public void refreshRight(){
        redisUtil.del(CacheKeyEnum.AUTH);
    }
    public void refreshUserMenuCache(String rightKey, String rightType, int orgId){
        String key = getKey(rightKey, rightType, orgId);
        redisUtil.delHash(CacheKeyEnum.AUTH, key);
    }

}
